using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CMS.api.Data;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using CMS.api.Fliters;
using CMS.api.Model;

namespace CMS.api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        private string allowCors = "AllowCors";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            // 注册数据库上下文到容器
            services.AddDbContext<CMSDb>(o => o.UseSqlServer());
            // 注册对数据库的基本操作服务到容器
            services.AddScoped(typeof(ICURDable<>), typeof(EfCURD<>));

            // 添加授权的验证服务
            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    // 是否要求使用https
                    option.RequireHttpsMetadata = false;
                    // 是否保存token
                    option.SaveToken = true;

                    // 使用配置中间件，获得token的配置
                    var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();

                    option.TokenValidationParameters =
                        new TokenValidationParameters
                        {
                            ValidateIssuer = true,  // 要不要验证发行token的人（个人或者组织）
                            ValidateAudience = false, // 是否验证受众
                            // ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,  //要不要验证生成token的密钥
                            ValidIssuer = tokenParameter.Issuer,
                            // ValidAudience = "user",
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret))
                        };
                        
                });

            //添加cors 服务 配置跨域处理
            services.AddCors(x =>
                {
                    x.AddPolicy(allowCors, builder =>
                         {
                             builder
                                 .AllowAnyOrigin() //允许任何来源的主机访问
                                 .AllowAnyMethod()
                                 .AllowAnyHeader();
                             // .AllowCredentials(); //指定处理cookie
                         });
                });

            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });

            services
                .AddSwaggerGen(c =>
                {
                    c
                        .SwaggerDoc("v1",
                        new OpenApiInfo
                        {
                            Title = "CMS.api",
                            Version = "v1"
                        });
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app
                    .UseSwaggerUI(c =>
                        c
                            .SwaggerEndpoint("/swagger/v1/swagger.json",
                            "CMS.api v1"));
            }

            app.UseRouting();

            // 登录验证
            app.UseAuthentication();
            // 授权
            app.UseAuthorization();
            // 使用允许跨域请求
            app.UseCors(allowCors);

            app
                .UseEndpoints(endpoints =>
                {
                    // 配置服务实现
                    endpoints.MapControllers();
                });
        }
    }
}
